<template>
	<view class="home-container">
		<!-- 定位 -->
		<view class="city-box" @tap="openWXAuth">
			<text class="city-detail">{{cityText}}</text>
			<u-icon name="arrow-down-fill" size="12"></u-icon>
		</view>
		<!-- swiper -->
		<Swiper />
		<!-- navbar -->
		<Navbar />
		<!-- 推荐文章 -->
		<Article />
	</view>
</template>

<script>
	import Swiper from './components/Swiper/Swiper.vue'
	import Navbar from './components/Navbar/Navbar.vue'
	import Article from './components/Article/Article.vue'
	
	var QQMapWX = require('@/libs/qqmap-wx-jssdk.min.js')
	var qqmapsdk = new QQMapWX({
		key: 'TLRBZ-7XM6P-YQ5DV-L47TN-HN3UJ-K5BPM'
	})
	export default {
		components: {
			Swiper,
			Navbar,
			Article
		},
		data() {
			return {
				cityText: '正在定位...',
				location: {}
			}
		},
		onShow() {
			this.getAddress()
		},
		methods: {
			getAddress() {
				const _that = this
				uni.getLocation({
					type: 'gcj02',
					success: function(res) {
						Object.assign(_that.location, {
							longitude: res.longitude,
							latitude: res.latitude
						})
						_that.getCityAddress()
					},
					fail(err) {
						_that.cityText = '定位失败'
					}
				});
			},
			getCityAddress() {
				const that = this
				qqmapsdk.reverseGeocoder({
					location: that.location,
					get_poi: 1,
					success: (res) => {
						that.cityText = res.result?.address
					},
					fail: (err) => {
						_that.cityText = '定位失败'
					}
				})
			},
			openWXAuth() {
				const _that = this
				uni.authorize({
					scope: 'scope.userLocation',
					success() {
						console.log('授权成功');
					},
					fail() {
						uni.showModal({
							content: '检测到您没打开定位功能权限，是否去设置打开？',
							confirmText: "确认",
							cancelText: "取消",
							success: function(res) {
								console.log(res);
								if (res.confirm) {
									uni.openSetting({
										success: (res) => {
											_that.getAddress()
										}
									})
								} else {
									_that.cityText = '定位失败'
								}
							}
						});
					}
				})

			}
		}
	}
</script>

<style lang="scss" scoped>
	.home-container {
		padding-left: 10rpx;
		padding-right: 10rpx;
	}

	.city-box {
		width: 100%;
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		margin-top: 30rpx;
		font-size: 24rpx;

		.city-detail {
			padding-right: 10rpx;
		}
	}
</style>